﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.IO;
using System.Data;
using System.Windows.Forms;
namespace DataAccessLayer.Adapter
{
    public class BackupAndRestoreAdapter
    {
        clsKetNoiCSDL kn = new clsKetNoiCSDL();
        SqlConnection con = new SqlConnection();
        public void BackupDataBase(string path)
        {
            if (path.Trim() != string.Empty)
            {
                if (!Directory.Exists(Path.GetDirectoryName(path)))
                {
                    MessageBox.Show("Thư mục không tồn tại!", "Thông báo!");
                }
                else
                {
                    try
                    {
                        //con = kn.getConnect();
                        string sql = "tbBackupDatabase";
                        int Npa = 1;
                        string[] name = new string[Npa];
                        object[] value = new object[Npa];
                        name[0] = "@Path"; value[0] = path;
                        kn.UpdateDL(sql, name, value, Npa);
                    }
                    catch
                    {
                        return;
                    }
                }
            }
            else
            {
                return;
            }
        }
        public void RestoreDatabase(string NameDirectory)
        {
            if (NameDirectory.Trim() != string.Empty)
            {
                if (!File.Exists(NameDirectory))
                {
                    return;
                }
                else
                {
                    try
                    {
                        string sql = @"Alter database CSDL_LuanAnFinal 
                                    set offline with rollback immediate 
                                    use master restore database CSDL_LuanAnFinal 
                                    from disk = @NameDirectory with replace 
                                    alter database CSDL_LuanAnFinal set online";
                        
                        con = kn.getConnect();
                        SqlCommand comd = new SqlCommand(sql, con);
                        comd.CommandType = System.Data.CommandType.Text;
                        comd.Parameters.Add(new SqlParameter("NameDirectory", SqlDbType.NVarChar)).Value = NameDirectory;
                        comd.ExecuteNonQuery();

                    }
                    catch
                    {
                        //MessageBox.Show("Không thể Restore: " + ex.Message);
                        return;
                    }
                    finally
                    {
                        con.Close();
                    }
                }
            }
        }
    }
}
